package com.polaris.live.ui.main.game

import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.cache.CommonCache
import com.polaris.live.common.adapter.ViewPagerAdapter
import com.polaris.live.common.cacha.DisplayUtil
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.databinding.FragmentHomeCenterGameBinding
import com.polaris.live.resp.back_resp.PartyGameResp
import com.polaris.live.resp.back_resp.UserPartyGameTaskResp
import com.polaris.live.translation.R
import com.polaris.live.ui.game.GameUtils
import com.polaris.live.utils.StartLiveProxy
import com.polaris.live.utils.interfaces.OnAutoRefreshListener
import com.polaris.live.utils.interfaces.OnRefreshStateListener
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.viewmodel.home.HomeGameViewModel
import com.polaris.live.widget.tab.OnPageSelectedListener
import com.polaris.live.widget.tab.OnTabSelectListener
import com.polaris.live.widget.tab.TabBean

/**
 * HomeCenterGameFragment
 *
 * @author Created by 半仙 on 2024/3/14/014 14:28
 */
class HomeCenterGameFragment : BaseVbFragment<HomeGameViewModel, FragmentHomeCenterGameBinding>(),
    OnAutoRefreshListener, OnRefreshStateListener {

    private val mFragments = ArrayList<Fragment>()

    private val mTitles = ArrayList<TabBean>()

    private var mGameList: List<PartyGameResp>? = null

    private var mPartyTaskResp: UserPartyGameTaskResp? = null

    private lateinit var mTabAdapter: ViewPagerAdapter

    //是否有数值游戏
    private var mIsHavaNumerGame = false

    override fun initView(savedInstanceState: Bundle?) {
        updateImmersionBar()

        initFragment()

        initObserver()
        initListener()
        isNeedHideLoading()
    }

    override fun onResume() {
        super.onResume()
        mIsHavaNumerGame = !GameUtils.getLiveCacheGameList().isNullOrEmpty()
    }

    private fun initFragment() {
        val page = DisplayUtil.getSecondaryPagesByPrimaryPage(DisplayUtil.GAME)
        page?.secondaryPages?.forEach {
            when (it) {
                DisplayUtil.GAME_MATCH -> {
                    mTitles.add(TabBean(StringUtils.getString(R.string.all)))
                    mFragments.add(HomeGameFragment())
                }
            }
        }

        mBinding.tab.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                mBinding.pager.currentItem = position
            }

            override fun onTabReselect(position: Int) {
                onAutoRefresh()
            }
        })
        mBinding.tab.setOnPageSelectedListener(object : OnPageSelectedListener {
            override fun onSelected(position: Int) {
                mBinding.rank.visibility = View.VISIBLE
                if (position == 0) {
                    if (!mIsHavaNumerGame) {
                        mBinding.rank.visibility = View.INVISIBLE
                    }
                }
            }

            override fun onDeselected(position: Int) {
            }
        })

        mTabAdapter = ViewPagerAdapter(mFragments, this)
        mBinding.pager.apply {
            adapter = mTabAdapter
            offscreenPageLimit = 5
        }
        mBinding.tab.setViewPage(mBinding.pager)
        mBinding.tab.setTabs(mTitles, mBinding.svScroll)

        val partyGameResp = CommonCache.getPartyGame()
        if (partyGameResp != null) {
            mGameList = partyGameResp
            initTitle()
        }
        mViewModel.getPartyGame()
    }

    private fun initListener() {
        mBinding.rank.setOnSingleClickListener {
            if (mBinding.pager.currentItem == 0 && mIsHavaNumerGame) {
                if (UserManager.isSafeUser()) {
                    Router.builder(RoutePath.USER_RANK_ACTIVITY)
                        .withInt("page", 2)
                        .navigation(requireActivity())
                }
            } else {
                if (mGameList?.isNotEmpty() == true) {
                    Router.builder(RoutePath.USER_GAME_RANK_ACTIVITY)
                        .withString("gameResp", JsonUtils.toJson(mGameList))
                        .withInt("page", mBinding.pager.currentItem)
                        .navigation(requireActivity())
                }
            }
        }
    }

    private fun initObserver() {
        mViewModel.mPartyGameLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mGameList = it
                //如果本地存储的数据数量  与  服务端返回的数据数量不一致  则移除之前的用新的
                val cacheList = CommonCache.getPartyGame()
                val isReAddFragment = it.isNotEmpty() && it.size != cacheList?.size
                if (isReAddFragment) {
                    mTitles.clear()
                    mFragments.clear()
                    mTitles.add(TabBean(StringUtils.getString(R.string.all)))
                    mFragments.add(HomeGameFragment())
                    initTitle()
                }
                //此处的顺序不可以变   因为要先做判断再替换数据
                CommonCache.setPartyGame(JsonUtils.toJson(it))
            })
        }
        mViewModel.mPartyRoomLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.roomId?.isNotEmpty() == true) {
                    val liveType = UserManager.getUser().live?.liveType
                    StartLiveProxy.builder(this)
                        .recoverLive(mViewModel, liveType, it.roomId)
                } else {
                    //开启派对
                    Router.builder(RoutePath.SET_PARTY_COVER_ACTIVITY)
                        .navigation(requireActivity())
                }
            })
        }
    }

    private fun initTitle() {
        val indexOfFirst = mFragments.indexOfFirst { it is OtherGameFragment }
        if (indexOfFirst != -1) return

        mGameList?.forEach {
            mTitles.add(TabBean(it.name))
            mFragments.add(OtherGameFragment().apply {
                arguments = bundleOf(
                    "gameResp" to it,
                )
            })
        }

        mBinding.tab.setTabs(mTitles, mBinding.svScroll)
        mTabAdapter.setFragments(mFragments)
        isNeedHideLoading()

        if (mFragments.isEmpty()) return
        mFragments.forEach { item ->
            if (item is OtherGameFragment) {
                item.onPartyTaskListCallback(mPartyTaskResp)
            }
        }
    }

    override fun onAutoRefresh() {
        if (!isCreated() || !isLoadData()) {
            return
        }
        val fragment = mFragments.getOrNull(mBinding.pager.currentItem) ?: return
        if (fragment is OnAutoRefreshListener) {
            (fragment as OnAutoRefreshListener).onAutoRefresh()
        }
    }

    override fun onRefreshState() {
        if (isCreated()) {
            val fragment = mFragments[mBinding.pager.currentItem]
            if (fragment is OnRefreshStateListener) {
                fragment.onRefreshState()
            }
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            updateImmersionBar()
        }
    }

    private fun updateImmersionBar() {
        NavigationBarUtils.setImmersionBarForMain(this, mBinding.homeGameTab)
    }

    private fun isNeedHideLoading() {
        if (mFragments.isNotEmpty()) {
            mBinding.loadingView.visibility = View.GONE
        }
    }
}